<?php
// Necesito extender Zend_Db_Table_Abstract para hacer la conversion de case en los nombres de los campos
class Ext_Db_Table extends Zend_Db_Table_Abstract
{
    /**
     * Classname for row
     *
     * @var string
     */
    protected $_rowClass = 'Ext_Db_Table_Row';
    /**
     * Classname for rowset
     *
     * @var string
     */
    protected $_rowsetClass = 'Ext_Db_Table_Rowset';

    const DEFAULT_DATE_FORMAT = 'dd/mm/yyyy';

    /**
     * if hasEnd date then don't delete set the end date on delete
     * @var boolean
     */
    protected $_useEndDate = false;

    /**
     * initalized with config from registry.
     * @var Zend_Config
     */
    private $_config = null;

    /**
     * initalized with user from Zend_Auth.
     * @var Zend_Config
     */
    private $_user = null;

    /**
     * Initialize object
     *
     * Called from {@link __construct()} as final step of object instantiation.
     *
     * @return void
     */
    public function init()
    {
        parent::init();
        
        // La unica forma de manejar las sequencias en mysql es con auto_increment
        // El default usage que tenemos es para Oracle sin triggers (o sea declaramos el nombre de la secuencia)
        // asi que esto es una especie de hack
        if ( $this->_db instanceof Zend_Db_Adapter_Mysqli && is_string( $this->_sequence ) ) {
            $this->_setSequence( true );
        }
    }

    public function getConfig() {
		
		if ( $this->_config === null ) {
        	$this->_config = Zend_Registry::get( "config" );
		}
        return $this->_config;
    }

    public function getUser() {
		if ( $this->_user === null ) {
			$auth = Zend_Auth::getInstance();
			if ( $auth->hasIdentity() ) {
				$this->_user = $auth->getIdentity();
			}
		}
        return $this->_user;
    }


    /**
     * Deletes existing rows.
     *
     * @param  array|string $where SQL WHERE clause(s).
     * @return int          The number of rows deleted.
     */
    public function delete($where)
    {
        if ( $this->_useEndDate ) {
            $now =  new Ext_Db_Date( Ext_Db_Date::NOW );
            return $this->update( array( "end_date" => $now ) , $where );
        }
        return parent::delete( $where );
    }

    /**
     * unDeletes existing rows if this table supports end_date.
     *
     * @param  array|string $where SQL WHERE clause(s).
     * @return int          The number of rows deleted.
     */
    public function unDelete($where)
    {
        if ( $this->_useEndDate ) {
            return $this->update( array( "end_date" => null ) , $where );
        }
        return 0;
    }
}
